﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.GestionDeUsuarios;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Collections.Generic;
using System.Web;
using System.IO;
using MS.InformationManagement.DAL.RecordCenter;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public class UserUpdateEventArgs : EventArgs
    {
        public int UserId { get; set; }
    }

    public partial class GestionDeUsuariosUserControl : BaseControl, IGestionDeUsuariosView
    {
        #region fields

        private GestionDeUsuariosPresenter _presenter;


        #endregion

        #region Properties

        public SPUser SelectedUser { get; set; }
        public int CurrentId
        {
            get
            {
                if (string.IsNullOrEmpty(Cache["CurrentUserId"].ToString()))
                    return -1;
                else
                    return int.Parse(Cache["CurrentUserId"] + "");
            }
        }
        public string CedulaUsuario { get; set; }
        public string NombreUsuario { get; set; }
        public string ApellidoUsuario { get; set; }
        public string TelefonoUsuario { get; set; }
        public string UbicacionUsuario { get; set; }
        public string Observaciones { get { return txtObservaciones.Text; } set { txtObservaciones.Text = value; } }
        public string EmailUsuario { get; set; }
        public string DepartamentoUsuario { get; set; }
        public List<VincularPerfiles> AllPerfiles { get; set; }
        public bool SucceedUpdate { get; set; }
        public TaxonomyFieldValue TaxonomyFieldValueDepartamento { get; set; }
        public string UserPerfil { get; set; }
        public bool HaveLibrary { get; set; }
        public bool HideControl { get; set; }
        public int IdPerfil { get; set; }
        public List<Roles> ListRoleByPerfil { get; set; }
        public IEnumerable<Seccion> ListSubSecciones { get; set; }
        string MessageLibraryNotFound = "El usuario no cuenta con una biblioteca en el sistema.<br>La biblioteca se creara automáticamente al actualizar su información.";
        public TaxonomyFieldValue UserPais { get; set; }

        #endregion

        #region Form Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            btnUpdate.AddLoader();
            lblInfo.Text = string.Empty;
            txtCedula.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValBtnUpdate", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            txtUbicacion.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValBtnUpdate", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            txtTelefono.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValBtnUpdate", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            txtObservaciones.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValBtnUpdate", AjaxControlToolkit.ValidatorCalloutPosition.Right);
            ddlPerfiles.Required(ExceptionConstants.ERROR_DDL_OBLIGATORIO, "ValBtnUpdate", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            deptSelector.SetRequired("ValBtnUpdate");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new GestionDeUsuariosPresenter(this);
            ShowForEdit(true);
        }

        public void hideResult(bool result)
        {
            pnlInfo.Visible = result;
            loadControl();
        }

        private void loadControl()
        {
            if (CurrentId >= 0)
            {
                _presenter.HandleLoad();
            }
        }

        protected void Action_Update(object sender, EventArgs e)
        {
            try
            {
                SelectedUser = MS.InformationManagement.Support.PeopleHelper.GetUserById(CurrentId);
                lblInfo.Text = string.Empty;
                CedulaUsuario = txtCedula.Text;
                TelefonoUsuario = txtTelefono.Text;
                UbicacionUsuario = txtUbicacion.Text;
                DepartamentoUsuario = deptSelector.SelectedDeparmentName;// ddlSubSeccion.SelectedItem.Text;
                UserPerfil = ddlPerfiles.SelectedItem.Text;
                //UserPais = TermsPaisSelectors.SelectedTerm;
                //string campo = UserPais.Label + "--" + UserPais.TermGuid;
                _presenter.HandleUpdate();
                if (OnUserUpdated != null) OnUserUpdated(this, new UserUpdateEventArgs { UserId = CurrentId });
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void ddlPerfilUsuario(object sender, EventArgs e)
        {
            UserPerfil = ddlPerfiles.SelectedItem.Text;
            _presenter.RequestRoles();
        }

        private void ShowForEdit(bool estado)
        {
            btnUpdate.Visible = estado;
            //btnCancelar.Visible = estado;
            txtCedula.Enabled = estado;
            txtTelefono.Enabled = estado;
            ddlPerfiles.Enabled = estado;
            txtObservaciones.Enabled = estado;
            txtUbicacion.Enabled = estado;
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            try
            {
                txtCedula.Text = CedulaUsuario;
                txtNombres.Text = NombreUsuario + " " + ApellidoUsuario;
                txtTelefono.Text = TelefonoUsuario;
                txtUbicacion.Text = UbicacionUsuario;
                txtEmail.Text = EmailUsuario;

                ddlPerfiles.DataSource = AllPerfiles;
                ddlPerfiles.DataBind();

                ddlPerfiles.Items.Insert(0, new ListItem("-- SELECCIONE --", "0"));
                TryToSetUserPerfil();
                TryToSetSubSeccion();

                rptRoles.DataSource = ListRoleByPerfil;
                rptRoles.DataBind();

                if (HaveLibrary == false)
                {
                    lblInfo.Text = MessageLibraryNotFound;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        private void TryToSetUserPerfil()
        {
            try
            {
                ddlPerfiles.SelectedValue = UserPerfil.ToUpper();
            }
            catch (Exception ex)
            {
                rptRoles.DataSource = null;
                rptRoles.DataBind();
                throw new Exception("El perfil asociado al usuario no existe. Por favor reasigne el perfil");
            }
        }

        private void TryToSetSubSeccion()
        {
            try
            {
                deptSelector.SelectedDeparmentName = DepartamentoUsuario.ToUpper();
                deptSelector.SetSelectionByName();
                //ddlSubSeccion.SelectedValue = DepartamentoUsuario.ToUpper();
            }
            catch (Exception ex)
            {
                rptRoles.DataSource = null;
                rptRoles.DataBind();
                throw new Exception("La dependencia asociada al usuario no existe. Por favor reasigne la dependencia");
            }
        }

        public void Result()
        {
            try
            {
                if (SucceedUpdate == true)
                {
                    this.HandleSuccess(GlobalConstants.SUCCESS_USER_UPDATE, null);
                    //ShowForEdit(false);
                    //btnEditar.Visible = true;
                    SelectedUser = MS.InformationManagement.Support.PeopleHelper.GetUserById(CurrentId);
                    txtObservaciones.Text = string.Empty;
                    //_presenter.HandleLoad();  
                }
                else
                {
                    this.HandleWarning("Ha ocurrido un error al actualizar la información");
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        public void UpdateRoles()
        {
            try
            {
                rptRoles.DataSource = ListRoleByPerfil;
                rptRoles.DataBind();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        #endregion

        public delegate void UserUpdateHanlder(object sender, UserUpdateEventArgs e);
        public event UserUpdateHanlder OnUserUpdated;

    }
}
